package io.xxx.xbutler.core.event.job;

import io.xxx.xbutler.constant.Formats;
import jakarta.annotation.Nonnull;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Component
public class CallbackDataCleanJob extends QuartzJobBean {

    @Value("${callback.directory:cdata}")
    private String directory;

    @Value("${callback.data.clean.date:7}")
    private Integer date;

    @Override
    protected void executeInternal(@Nonnull JobExecutionContext context) {
        LocalDate now = LocalDate.now();
        Path dir = Paths.get(directory);
        try (Stream<Path> walk = Files.walk(dir)) {
            List<Path> paths = walk
                    .filter(Files::isRegularFile)
                    .toList();
            for (Path path : paths) {
                String name = path.toFile().getName();
                LocalDate date = LocalDate.parse(name, Formats.COMPACT_DATE_FORMATTER);
                LocalDate cutoff = now.minusDays(this.date);
                if (date.isBefore(cutoff)) {
                    boolean result = Files.deleteIfExists(path);
                    if (result) {
                        log.info("回调数据文件已删除[path:{}]", path);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
